from urllib import request, parse
import json


def youdao(key):
    '''封装函数'''
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
    # 定义请求参数
    data = {
        'i': key,
        'form': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': '1536313394645',
        'sign': '1ded35de5e131af794f4097bff760513',
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTIME',
        'typoResult': 'false',
    }
    data = parse.urlencode(data)  # 编码转换
    # 封装headers头信息
    headers = {
        'Content-Length': len(data)
    }
    try:
        # 发送请求，抓取信息
        req = request.Request(url=url, data=bytes(
            data, encoding='utf-8'), headers=headers)
        res = request.urlopen(req)
        # 解析结果并输出
        str_json = res.read().decode('utf-8')  # json
        myjson = json.loads(str_json)  # 把json转字典
        info = myjson['translateResult'][0][0]['tgt']
        print(info)
    except Exception as e:
        if hasattr(e, 'code'):
            print('HTTPError')
            print(e.reason)
            print(e.code)
        elif hasattr(e, 'reason'):
            print(e.reason)
        else:
            print(e)


if __name__ == '__main__':
    while True:
        key = input('请输入需要翻译的文字(q退出)：')
        if key == 'q':
            print('退出')
            break
        youdao(key)
